package com.baixiaowen.xiaoaointerview.并发基础篇;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * 小明向小红鞠躬
 *
 * @author Baixiaowen
 */
public class DeadLock {

    static class Friend {
        private final String name;
        private final ReentrantLock lock = new ReentrantLock();

        public Friend(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public void bow(Friend bower) {
            // Protocol
            try {
                lock.tryLock(1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread.currentThread().interrupt();
            System.out.format("%s: %s 向我鞠躬!%n", this.name, bower.getName());
            lock.unlock();
            bower.bowBack(this);
        }
        public void bowBack(Friend bower) {
            lock.lock();
            System.out.format("%s: %s"
                            + " 回了我!%n",
                    this.name, bower.getName());
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {

//         A, B
//         A.bow -> A -> tryB -> releaseA
//         B.bow -> B -> tryA
        final Friend xiaoming =
                new Friend("小明");
        final Friend xiaohong =
                new Friend("小红");
        new Thread(() -> xiaoming.bow(xiaohong)).start();
        new Thread(() -> xiaohong.bow(xiaoming)).start();
        
    }

}
